package com.nicole.service.impl;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.nicole.entity.SysConfig;
import com.nicole.mapper.SysConfigMapper;
import com.nicole.service.SysConfigService;
import com.nicole.utils.Convert;
import com.nicole.utils.RedisCache;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class SysConfigServiceImpl implements SysConfigService {

    @Resource
    private RedisCache redisCache;

    @Resource
    private SysConfigMapper sysConfigMapper;

    /**
     * 项目启动时 将系统参数缓存到redis
     */
    @PostConstruct
    public void initSysParams() {
        log.info("========初始化系统参数===========");
        List<SysConfig> configList = sysConfigMapper.getSysConfigList(new SysConfig());
        for (SysConfig config : configList) {
            redisCache.setCacheObject(config.getConfigKey(), config.getConfigValue());
        }
    }

    /**
     * 获取验证码参数是否开启
     */
    public boolean getCaptchaEnable() {
        String configValue = getConfigValueByKey("sys.account.captchaEnabled");
        if (StrUtil.isEmpty(configValue)) {
            return true;
        }
        return Convert.toBool(configValue);
    }


    /**
     * 根据参数键名获取参数值
     * @param key 参数key
     * @return 参数value
     */
    @Override
    public String getConfigValueByKey(String key) {
        String keyValue = Convert.toStr(redisCache.getCacheObject(key));
        if(StrUtil.isNotEmpty(keyValue)){
            return keyValue;
        }
        SysConfig sysConfigByKey = sysConfigMapper.getSysConfigByKey(key);
        if(ObjUtil.isNotNull(sysConfigByKey)){
            redisCache.setCacheObject(key, sysConfigByKey.getConfigValue());
            return sysConfigByKey.getConfigValue();
        }
        return null;
    }
}
